package cn.pconline.autoclub.service;

import java.util.Date;

import org.gelivable.auth.entity.GeliSession;
import org.gelivable.auth.entity.GeliUser;
import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.SqlBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;

import cn.pconline.autoclub.entity.UpgradeRule;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.r.client.SimpleHttpTemplate;

/**
 * Service-车友会升星规则
 * @author zhoutianhuai
 */
public class UpgradeRuleService {

    @Autowired
    private GeliDao geliDao;
    @Autowired
    private GeliOrm geliOrm;
    @Autowired
    private PagerService pagerService;
    @Autowired
    private UserService userService;
    @Autowired
    private SimpleHttpTemplate simpleHttpTemplate;
    private static final Logger log = LoggerFactory.getLogger(UpgradeRuleService.class);
    
    
    public long createUpgradeRule(UpgradeRule upgradeRule) {
        GeliUser user = GeliSession.getCurrentUser();
        if (user != null) {
        	upgradeRule.setCreateBy(user.getUserId());
        }
        upgradeRule.setCreateAt(new Date());
        return geliDao.create(upgradeRule);
    }
      
    public int updateUpgradeRule(UpgradeRule upgradeRule) {
    	upgradeRule.setUpdateAt(new Date());
        GeliUser u = GeliSession.getCurrentUser();
        long uid = 0;
        if (u != null) {
            uid = u.getUserId();
        }
        upgradeRule.setUpdateBy(uid);
        return geliDao.update(upgradeRule);
    }
    
    public UpgradeRule findUpgradeRule(long id) {
        try {
            return geliDao.find(UpgradeRule.class, id);
        } catch (DataAccessException ex) {
            return null;
        }
    }
    
    public UpgradeRule findUpgradeRuleByLevelId(long levelId) {
    	 SqlBuilder sql = new SqlBuilder();
         sql.appendSql("select * from ").appendSql(geliOrm.getTableName(UpgradeRule.class));
         sql.appendSql(" where level_id = ").appendValue(levelId);
         sql.appendSql(" and status != ").appendValue(UpgradeRule.STATUS_DELETE);
         return geliDao.findFirst(UpgradeRule.class, sql.getSql(), sql.getValues());
    }
    
    public Pager<UpgradeRule> pageUpgradeRule(int pageNo, int pageSize) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select rule_id from ").appendSql(geliOrm.getTableName(UpgradeRule.class));
        sql.appendSql(" where status != ").appendValue(UpgradeRule.STATUS_DELETE);
        sql.appendSql(" order by level_id");
        return pagerService.pager(UpgradeRule.class, sql, pageNo, pageSize);
    }
    
}
